<template>
    <h3>扫描</h3>
    <video class="video-box" ref="videoRef" autoplay></video>
</template>

<script setup lang="ts">
import { shallowRef, onMounted } from "vue";
import * as faceApi from "face-api.js";

const videoRef = shallowRef<HTMLVideoElement | null>(null);

const loadModel = async () => {
    await faceApi.nets.tinyFaceDetector.loadFromUri("/public/models");
    await faceApi.nets.faceLandmark68Net.loadFromUri("/public/models");
    await faceApi.nets.faceRecognitionNet.loadFromUri("/public/models");
    await faceApi.nets.faceExpressionNet.loadFromUri("/public/models");
}


const startVideo = async () => {
    const video = videoRef.value;
    if (!video) return
    navigator.mediaDevices.getUserMedia({
        video: true,
    }).then(steam => {
        video.srcObject = steam;
        video.onloadedmetadata = () => {
            video.play();
        };
    });

}

const detectFace = async () => {
    const video = videoRef.value;
    if (!video) return

    const detections = await faceApi.detectAllFaces(video).withFaceLandmarks().withFaceExpressions();

    if (detections.length) {
        const expression = detections[0].expressions;
        console.log(expression)
    }

    requestAnimationFrame(detectFace);
}

const init = async () => {
    await loadModel();
    await startVideo();
    detectFace();
}


onMounted(() => {
    init();
})


</script>
<style scoped>
.video-box {
    width: 100%;
    height: 90vh;
    border: 1px solid #000;
}
</style>